#!/usr/bin/python
# -*- coding: utf-8 -*-
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from check_ui import Ui_Form as Ui_CheckWindow
from openpts_ui import Ui_MainWindow
from createdb import libdatabase
import sys

class CheckDialog(QDialog, Ui_CheckWindow):
    def __init__(self, examdata, personid, database):
        """
            starting to get the checkdata
            with examid
        """
        QDialog.__init__(self)
        self.setupUi(self)
        self.database = database
        examid = examdata[0]
        b= self.database.getCheckData(examid, personid)
        x = 0
        self.checklist = []
        while x < len(b):
             self.tableWidget.setRowCount(len(b))
             self.checklist.append(b[x])
             ab = QTableWidgetItem(b[x][3])
             ac = QTableWidgetItem(b[x][4])
             ad = QTableWidgetItem(b[x][5])
             self.tableWidget.setItem(x, 0, ab)
             self.tableWidget.setItem(x, 1, ac)
             self.tableWidget.setItem(x, 2, ad)
             x += 1

class Person:
    def __init__(self, id, name):
        self.name = name
        self.id = id

class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setupUi(self)
        self.connect(self.searchwidget, SIGNAL("itemSelectionChanged()"), self.fill_data)
        self.connect(self.newpatient, SIGNAL("clicked()"), self.clean_data) #new button
        self.connect(self.save, SIGNAL("clicked()"), self.add_data) #save button
        self.connect(self.checkButton, SIGNAL("clicked()"), self.check_open)
        self.connect(self.tableWidget, SIGNAL("cellClicked(int,int)"), self.exam_fill_data)
        #Adding names
        self.database = libdatabase()
        try:
            self.database.start()
        except:
            pass
        #print self.database.showNames()
        #Exaimple
        #self.database.addPersonaldata("Taha Doğan Güneş", "1","05.02.1994","Toki","Tokat,",
        #                             "Merkez","0123","123","213","123","good")

        self.refresh_list()
        #this is for the persons
        self.listdata = []
        #this is for the exam data
        self.examlist = []
       
        self.populateList()
        self.currentpid = None
        #print self.tabWidget.currentIndex()
    def exam_fill_data(self, row, col):
        data = self.examlist[row]
        self.examdate.setText(data[1])
        self.examdiagnosis.setText(data[2])
        self.examfinding.setText(data[3])
        if data[4] == "Conservative":
	    self.examtype.setCurrentIndex(0)
	else:
	    self.examtype.setCurrentIndex(1)
    def check_open(self):
        for i in self.examlist:
            print i[0],i[1],i[2]
        checkdialog = CheckDialog(self.examlist[self.tableWidget.currentRow()], self.currentpid, self.database)
        checkdialog.exec_()
    def populateList(self):
        b = self.database.getIDs()
        x = 0
        while x<len(b):
            person = Person(b[x][0], b[x][1])
            self.listdata.append(person)
            x = x + 1
        #print self.listdata
        #for i in self.listdata:
            #print i.id
    def clean_data(self):
        index = self.tabWidget.currentIndex()
        if index == 0:
            for i in [self.name,self.date, self.age,
                      self.address, self.town, self.province,
                      self.homephone, self.workphone, self.gsmphone,
                      self.notes]:
                i.setText("")
            self.gender.setCurrentIndex(0)
        elif index == 1:
            print "Exams-clean_data"
    def add_data(self):
        index = self.tabWidget.currentIndex()
        if index == 0:
            self.database.addPersonaldata(self.name.text(),
                                          self.gender.currentIndex(), 
                                          self.date.text(),
                                          self.address.toPlainText(),
                                          self.town.text(),
                                          self.province.text(),
                                          self.homephone.text(),
                                          self.workphone.text(),
                                          "",
                                          self.gsmphone.text(),
                                          self.notes.toPlainText())
            self.refresh_list()
        elif index == 1:
            self.database.addExamdata(self.searchwidget.row(self.searchwidget.currentItem())+1,
                                                           self.examdate.text(),
                                                           self.examfinding.text(),
                                                           self.examdiagnosis.text(),
                                                           self.examtype.currentText())
            
            self.exam_data()
        
    def refresh_list(self):
        self.searchwidget.clear()
        self.tableWidget.clearContents()
        for i in self.database.showNames():
            self.searchwidget.addItem(i)
        self.totalrecords.setText(str(len(self.database.showNames())))
    
    def exam_data(self):
        number = self.searchwidget.row(self.searchwidget.currentItem())+1
        self.currentpid = number
        b = self.database.getExamData(number)
        x = 0
        
        while x < len(b):
             self.tableWidget.setRowCount(len(b))
             self.examlist.append(b[x])
             ab = QTableWidgetItem(b[x][1])
             ac = QTableWidgetItem(b[x][2])
             ad = QTableWidgetItem(b[x][3])
             ae = QTableWidgetItem(b[x][4])
             self.tableWidget.setItem(x, 0, ab)
             self.tableWidget.setItem(x, 1, ac)
             self.tableWidget.setItem(x, 2, ad)
             self.tableWidget.setItem(x, 3, ae)
             x += 1
        if len(b) == 0:
            self.tableWidget.clearContents()
            self.tableWidget.setRowCount(len(b))

    def fill_data(self):
        #if "name"
        #name = self.searchwidget.currentItem()
        a = self.database.getByID((self.searchwidget.row(self.searchwidget.currentItem())+1))[0]
        b = self.database.getExamData((self.searchwidget.row(self.searchwidget.currentItem())+1))
        self.patientname.setText(a[1])
        self.name.setText( a[1])
        self.gender.setCurrentIndex(int(a[2]))
        self.date.setText(a[3])
        self.address.setText(a[5])
        self.town.setText(a[6])
        self.province.setText(a[7])
        self.homephone.setText(a[8])
        self.workphone.setText(a[9])
        self.gsmphone.setText(a[11])
        self.notes.setText(a[12])
        #time = a[3].split(".")
        #date = QDate(int(time[1]),int(time[0]), int(time[2]))
        #self.date.setDate(date)     
        self.age.setText(str(self.database.ageCalculator(a[3])))
        self.exam_data()

             
        
         
if __name__ == "__main__":

    app = QApplication(sys.argv)
    #locale = QtCore.QLocale.system().name()
    #translator = QTranslator()
    #translator.load("openpts_%s.qm" % locale)
    #app.installTranslator(translator)
    main_window = MainWindow()
    main_window.show()
    app.exec_()

